package ren.nearby.main.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


import com.jakewharton.rxbinding2.widget.RxTextView;
import com.orhanobut.logger.Logger;


import org.json.JSONObject;
import org.reactivestreams.Subscription;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


//import debug.MainApplication;
import co.mobiwise.materialintro.shape.Focus;
import co.mobiwise.materialintro.shape.FocusGravity;
import co.mobiwise.materialintro.view.MaterialIntroView;
import io.github.tonnyl.light.Light;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;
import ren.nearby.bean.beans.FromAndAction;
import ren.nearby.bean.beans.UserBean;
import ren.nearby.http.base.BaseActivity;
import ren.nearby.http.base.IPresenter;
import ren.nearby.http.di.data.ResponseCallBack;
import ren.nearby.http.meepo.Meepo;
import ren.nearby.http.meepo.config.UriConfig;
import ren.nearby.http.permission.Permission;
import ren.nearby.http.permission.RxPermissions;
import ren.nearby.http.utils.util.MD5Utils;
import ren.nearby.http.utils.util.PreferencesUtils;
import ren.nearby.http.utils.util.RequestJsonUtil;
import ren.nearby.http.utils.util.SecuritySharedPreference;
import ren.nearby.http.view.progress.NumberProgressBar;
import ren.nearby.main.ActivityRouter;
import ren.nearby.main.R;


/**
 * Created by Administrator on 2017/9/6 0006.
 */

public class LoginAct extends BaseActivity implements LoginContract2.View, ResponseCallBack,RxPermissions.PermissionsInterface {
    LoginAction action;
    LoginAction2 action2;
    EditText editZh;
    EditText editPwd;
    Button btnLogin;
    Button btnRegistered;
    Button btnCollection;
    Button btnTestToKen;
    Button btnTestEncr;
    Button main_btn_result;
    Button main_btn_progress;
    NumberProgressBar main_numberbar;

    @Override
    public Context getContext() {
        return this;
    }


    @Override
    public IPresenter getPresenter() {
        return action;
    }

    private static final String INTRO_CARD = "material_intro";

    @Override
    public void show() {

    }

    @Override
    public int getContentView() {
        return R.layout.main_login;
    }

    private void showIntro(View view, String usageId, String text) {
        new MaterialIntroView.Builder(LoginAct.this)
                .enableDotAnimation(true)
                //.enableIcon(false)
                .setFocusGravity(FocusGravity.CENTER)
                .setFocusType(Focus.MINIMUM)
                .setDelayMillis(200)
                .enableFadeAnimation(true)
                .performClick(true)
                .setInfoText(text)
                .setTarget(view)

//                .setShape(ShapeTyp.RECTANGLE)
                .setUsageId(usageId) //THIS SHOULD BE UNIQUE ID
                .show();
    }

    RxPermissions rxPermissions;

    public void singlePermissions() {
        rxPermissions.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).apply(new Observable<Object>() {
            @Override
            protected void subscribeActual(final Observer<? super Object> observer) {
                Logger.e("subscribeActual = ");
                observer.onNext(observer);


            }
        }).subscribe(new Observer<Permission>() {
            @Override
            public void onSubscribe(Disposable d) {
                Logger.e("onSubscribe = " + d.isDisposed());
            }

            @Override
            public void onNext(Permission permission) {
                Logger.e("onNext = " + permission.granted);

                if (permission.granted) {
                    Logger.e("已经授权的权限" + permission.name);
                } else if (permission.shouldShowRequestPermissionRationale) {
                    //拒绝
                    Logger.e("已经拒绝的权限" + permission.name);
                } else {
                    //拒绝 不再询问
                    Logger.e("不再询问的权限" + permission.name);
                }

            }

            @Override
            public void onError(Throwable e) {
                Logger.e("onError = " + e.toString());
            }

            @Override
            public void onComplete() {
                Logger.e("onComplete = ");
            }
        });
    }
    ActivityRouter router;

    @Override
    public void initView() {
        super.initView();
        builder
                .setIconLeft(R.mipmap.btn_back_white)
                .setBack(true)
                .setTitle(getResources().getString(R.string.main_login))
                .setBackgroundColor(R.color.colorPrimary)
                .setTitleColor(R.color.white)
                .build();
        final Meepo meepo = new Meepo.Builder()
                .config(new UriConfig().scheme("action").host("nearby.action"))
                .build();
        router = meepo.create(ActivityRouter.class);
        //组件模式的初始化
//        action = DaggerLoginContractComponent.builder()
//                .actionModule(new ActionModule(this))
//                .tasksRepositoryComponent(debug.MainApplication.getTasksRepositoryComponent())
//                .build()
//                .getAction();
//        Logger.e(action == null ? "1" : "0");

        //集成模式的初始化注入
//        action2 = DaggerLoginContractComponent2.builder()
//                .actionModule2(new ActionModule2(this))
//                .mainComponent(MainApplication.getMainComponent())
//                .build().getAction();
//        Logger.e(action2 == null ? "1" : "0");

//        DaggerLoginContractComponent2.builder()
//                .actionModule(new ActionModule(this))
//                .mainComponent(MainApplication.getMainComponent())
//                .build();


        rxPermissions = new RxPermissions(getActivity(),this);
        //测试请求权限
        singlePermissions();
        editZh = (EditText) findViewById(R.id.main_edit_zh);
        editPwd = (EditText) findViewById(R.id.main_edit_pwd);
        btnLogin = (Button) findViewById(R.id.main_btn_login);
        Observable<CharSequence> zhObservable = RxTextView.textChanges(editZh).skip(1);
        Observable<CharSequence> pwObservable = RxTextView.textChanges(editPwd).skip(1);
        Observable.combineLatest(zhObservable, pwObservable, zhObservable, new Function3<CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3) throws Exception {
                boolean isUserZh = !TextUtils.isEmpty(editZh.getText());
                boolean isUserPwd = !TextUtils.isEmpty(editPwd.getText());
                return isUserZh && isUserPwd;
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean o) throws Exception {
                Logger.e("提交按钮是否可点击： " + o);
                btnLogin.setEnabled(o);
            }
        });


        btnRegistered = (Button) findViewById(R.id.main_btn_registered);
        btnCollection = (Button) findViewById(R.id.main_btn_collection);
        btnTestToKen = (Button) findViewById(R.id.main_btn_test_token);
        btnTestEncr = (Button) findViewById(R.id.main_btn_test_encr);
        main_btn_result = findViewById(R.id.main_btn_result);
        main_btn_progress = (Button) findViewById(R.id.main_btn_progress);

        main_numberbar = (NumberProgressBar) findViewById(R.id.main_numberbar);
        showIntro(btnLogin, INTRO_CARD, "This is card! Hello There. You can set this text!");

//        Toasty.error(LoginAct.this, "This is an error toast.", Toast.LENGTH_SHORT, true).show();
        Light.info(btnTestEncr, "Info", Light.LENGTH_SHORT).show();

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String zh = editZh.getText().toString().trim();
                    String pwd = editPwd.getText().toString().trim();
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject json = new JSONObject();
                    json.put("userName", "111");
                    json.put("password", MD5Utils.MD5("123456"));
                    map.put("action", "add");
                    map.put("nonceStr", RequestJsonUtil.random());
                    map.put("content", json.toString());
                    map.put("controller", "user");
                    String stringATemp = RequestJsonUtil.sortByJoinKey(map, MD5Utils.MD5("123456"));
                    Logger.e("stringATemp = " + stringATemp);
                    String sign = MD5Utils.MD5(stringATemp);
                    Logger.e("sign = " + sign);
                    map.put("sign", sign);
                    Logger.e("request = " + new JSONObject(map).toString());
                    action.login(map, LoginAct.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });


        btnRegistered.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String zh = editZh.getText().toString().trim();
                    String pwd = editPwd.getText().toString().trim();
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject json = new JSONObject();
                    json.put("userName", "000" + new Random().nextInt(100));
                    json.put("password", MD5Utils.MD5("123456"));
                    map.put("action", "add");
                    map.put("nonceStr", RequestJsonUtil.random());
                    map.put("content", json.toString());
                    map.put("controller", "user");
                    String stringATemp = RequestJsonUtil.sortByJoinKey(map, MD5Utils.MD5("123456"));
                    Logger.e("stringATemp = " + stringATemp);
                    String sign = MD5Utils.MD5(stringATemp);
                    Logger.e("sign = " + sign);
                    map.put("sign", sign);
                    Logger.e("request = " + new JSONObject(map).toString());
                    PreferencesUtils.putString(LoginAct.this, "uuid", MD5Utils.MD5("123456"));
                    action.registered(map, LoginAct.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        btnCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject json = new JSONObject();
                    json.put("id", PreferencesUtils.getString(LoginAct.this, "id", "0"));
                    map.put("action", "search");
                    map.put("nonceStr", RequestJsonUtil.random());
                    map.put("content", json.toString());
                    map.put("controller", "user");
                    String stringATemp = RequestJsonUtil.sortByJoinKey(map, MD5Utils.MD5("123456"));
                    Logger.e("stringATemp = " + stringATemp);
                    String sign = MD5Utils.MD5(stringATemp);
                    Logger.e("sign = " + sign);
                    map.put("sign", sign);
                    Logger.e("request = " + new JSONObject(map).toString());
                    action.collection(map, LoginAct.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        btnTestToKen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Map<String, Object> map = new HashMap<String, Object>();
                    JSONObject json = new JSONObject();
                    json.put("token", "123456789");
                    json.put("phone", "18126060019");
                    map.put("action", "search");
                    map.put("nonceStr", RequestJsonUtil.random());
                    map.put("content", json.toString());
                    map.put("controller", "user");
                    String stringATemp = RequestJsonUtil.sortByJoinKey(map, MD5Utils.MD5("123456"));
                    Logger.e("stringATemp = " + stringATemp);
                    String sign = MD5Utils.MD5(stringATemp);
                    Logger.e("sign = " + sign);
                    map.put("sign", sign);
                    Logger.e("request = " + new JSONObject(map).toString());
                    action.testToken(map, LoginAct.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        btnTestEncr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                SecuritySharedPreference securitySharedPreference = new SecuritySharedPreference(getApplicationContext(), "nblock_sp", Context.MODE_PRIVATE);
                SecuritySharedPreference.Editor editor = securitySharedPreference.edit();
                editor.putString("u_", "18126060019");
                editor.putString("p_", "111111");
                editor.apply();

                SharedPreferences sharedPreferences = getSharedPreferences("nblock_sp", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor2 = sharedPreferences.edit();
                editor2.putString("u__", "18126060019");
                editor2.putString("p__", "111111");
                editor2.apply();
            }
        });
        final SharedPreferences sharedPreferences = getSharedPreferences("nblock_sp", Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor2 = sharedPreferences.edit();

//        interval(1000, new IRxNext() {
//            @Override
//            public void doNext(long number) {
//                String u__ = "18126060019-" + new Random().nextInt(10);
//                String p__ = "111111-" + new Random().nextInt(10);
//                Logger.e("写 - number = " + number + " u__ = " + u__ + " - p__ = " + p__);
//                editor2.putString("u__", u__);
//                editor2.putString("p__", p__);
//                editor2.apply();
//            }
//        });
//        interval(1000, new IRxNext() {
//            @Override
//            public void doNext(long number) {
//
//                String u__ = sharedPreferences.getString("u__", "0");
//                String p__ = sharedPreferences.getString("p__", "0");
//                Logger.e("读 - number = " + number + " - u__  = " + u__ + " - p__ = " + p__);
//            }
//        });

        resultStr = "one";
//        String value = testDebug2();


        main_btn_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("value1", "值1");
                map.put("value2", "值2");

//                router.gotoB(NWelcome.this, map);
                //多个参数传递与跳转Code与返回
                map.put("value3", "值3");
                router.gotoViewWelcome(getActivity(), map, 103);
            }
        });

        main_btn_progress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 测试 rxjava
                 * 作用
                 * 当两个Observables中的任何一个发送了数据后，
                 * 将先发送了数据的Observables 的最新（最后）一个数据 与
                 * 另外一个Observable发送的每个数据结合，
                 * 最终基于该函数的结果发送数据combineLatest
                 */
     /*           Observable.combineLatest(
                        Observable.just(1L, 2L, 3L),
                        Observable.intervalRange(0, 3, 1, 1, TimeUnit.SECONDS), new BiFunction<Long, Long, Long>() {
                            @Override
                            public Long apply(Long aLong, Long aLong2) throws Exception {
                                Logger.e("合并的数据是： "+ aLong + "  - "+ aLong2);
                                return aLong + aLong2;
                            }
                        })
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                Logger.e("合并的结果：" + aLong);
                            }
                        });*/
                /**
                 * 组合多个被观察者一起发送数据，合并后 按时间线并行执行
                 * 1.二者区别：组合被观察者的数量，即merge（）组合被观察者数量≤4个，而mergeArray（）则可＞4个
                 * 2.区别上述concat（）操作符：同样是组合多个被观察者一起发送数据，但concat（）操作符合并后是按发送顺序串行执行
                 */
                /*Observable.merge(
                        Observable.intervalRange(0, 3, 1, 1, TimeUnit.SECONDS), // 从0开始发送、共发送3个数据、第1次事件延迟发送时间 = 1s、间隔时间 = 1s
                        Observable.intervalRange(2, 3, 1, 1, TimeUnit.SECONDS)) // 从2开始发送、共发送3个数据、第1次事件延迟发送时间 = 1s、间隔时间 = 1s
                        .subscribe(new Observer<Long>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Long value) {
                                Logger.e("接收到了事件" + value);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e("对Error事件作出响应");
                            }

                            @Override
                            public void onComplete() {
                                Logger.e("对Complete事件作出响应");
                            }
                        });
*/

                action2.dowApk(LoginAct.this);
            }
        });
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //测试Meepo请求code返回
        Logger.e(" login main 组件 " + "requestCode = " + requestCode + " - resultCode = " + resultCode);
    }

    Subscription mSubscription;

    public interface IRxNext {
        void doNext(long number);
    }

    public void interval(long milliseconds, final IRxNext next) {
        Observable
                .interval(milliseconds, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        next.doNext(aLong);
                    }
                });

    }

    public String testDebug2() {
        return testDebug();
    }

    int result;
    String resultStr;

    public String testDebug() {
        int[] at = new int[]{0, 2, 3, 6, 8};
        for (int i = 0; i < 9; i++) {
            if (i % 2 == 0) {
                resultStr = " % = 0 " + i;
            } else {
                resultStr = "% != 0" + i;
            }
            result = i * i;
        }
//        Logger.e("测试关注异常 = "+at[5]);
        resultStr = "two";
        Logger.e("resultStr = " + resultStr);
        return resultStr;
    }


    @Override
    protected void onResume() {
        super.onResume();
        Logger.e(" onResume ");
    }


    @Override
    public void onDataStart(int action) {
        Logger.e("onDataStart");

        main_numberbar.setProgress(action);

    }

    @Override
    public void onDataFailure(int from, String error) {
        Logger.e("onDataFailure");
        switch (from) {
            case FromAndAction.From.LOGIN:
                Logger.e("LOGIN");

                break;
            case FromAndAction.From.REGISTERED:
                Logger.e("REGISTERED");
                break;
            case FromAndAction.From.TESTDOWAPK:
                Logger.e("TESTDOWAPK");

                break;
        }

    }

    @Override
    public void onToast(String message) {
        Logger.e(" message = " + message);
    }

    @Override
    public void onDataSuccess(int from, Object results) {
        Logger.e("onDataSuccess");
        switch (from) {
            case FromAndAction.From.LOGIN:
                UserBean userBean = (UserBean) results;
                Logger.e("onDataSuccess" + userBean.toString());
                Logger.e("LOGIN");
                break;
            case FromAndAction.From.REGISTERED:
                Logger.e("REGISTERED");

                break;
            case FromAndAction.From.TESTDOWAPK:
                Logger.e("TESTDOWAPK");
                if (results instanceof Integer) {

                } else if (results instanceof File) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判读版本是否在7.0以上
                        ApplicationInfo applicationInfo = getApplicationInfo();
                        String providerName = applicationInfo.packageName == null ?
                                "ren.nearby.main.fileprovider" : applicationInfo.packageName + ".fileprovider";
                        Uri apkUri = FileProvider.getUriForFile(this, providerName, (File) results);
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        startActivity(install);
                    } else {
                        Intent install = new Intent(Intent.ACTION_VIEW);
                        install.setDataAndType(Uri.fromFile((File) results), "application/vnd.android.package-archive");
                        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(install);
                    }
                }
                break;
        }
    }


}
